/*
 * Copyright (c) 2023, 2023,yzc.cn All rights reserved.
 *
 */
package cn.yzc;

import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * <p>Project: RabbitMQ - Consumer</p>
 * <p>Powered by yzc On 2023-12-25 21:20:12</p>
 * <p>描述：<p>
 *
 * @author yzc [yzc0415@126.com]
 * @version 1.0
 * @since 17
 */
@Component
public class Consumer {
    int num =10; //商品数量

    @Autowired
    RabbitTemplate rabbitTemplate;

    /**
     * 监听抢单队列 有 消息。 根据消息生成订单
     * @param message
     * @param channel
     */
    @RabbitListener(queues = {"normalQueue"})
    public void handlerApply(Message message, Channel channel){
        handler(message,channel);
    }

    synchronized void handler(Message message, Channel channel) {
        //判断商品的数量是否大于0
        if (num<=0){
            //说明商品卖完 剩下的消息拒绝
            try {
                channel.basicReject(message.getMessageProperties().getDeliveryTag(),false);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            return; //放回 不再继续执行
        }
        //还有商品数量
        String msg = new String(message.getBody());
        //msg由 用户id：商品id 格式组成
        String[] tmp = msg.split(":");
        String userId = tmp[0];
        String goodsId = tmp[1];

        //根据用户id和商品id查询是否有订单 如果有 （消息拒绝不在接受）

        String orderId = "dd2023-"+num;
        num--;
        System.out.println(Thread.currentThread().getName()+"生成订单"+orderId);

        //将消息发送到订单队列
        rabbitTemplate.send("orderExchange","orders",new Message(orderId.getBytes(StandardCharsets.UTF_8)));

        try {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @RabbitListener(queues = {"deadQueue"})
    public void handlerExpireOrder(Message message,Channel channel) throws IOException {
        System.out.println("订单判断"+new String(message.getBody())+"状态，并更新");
       // channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
    }



}
